package com.yd.quartz.controller;

import com.yd.quartz.domain.JobInfo;
import com.yd.quartz.handler.JobHander;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/job")
public class QuartzController {
    
    
    @Autowired
    private JobHander jobHander;
    
    @Autowired
    private Scheduler scheduler;


    /**
     * 获取所有任务
     */
    @RequestMapping("/all")
    public List<JobInfo> list() throws SchedulerException {
        List<JobInfo> jobInfos = new ArrayList<>();

        List<String> triggerGroupNames = scheduler.getTriggerGroupNames();

        for (String triggerGroupName : triggerGroupNames) {
            Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(triggerGroupName));

            for (TriggerKey triggerKey : triggerKeys) {
                Trigger trigger = scheduler.getTrigger(triggerKey);

                JobKey jobKey = trigger.getJobKey();

                JobInfo jobInfo = jobHander.getJobInfo(jobKey.getGroup(), jobKey.getName());
                jobInfos.add(jobInfo);
            }
        }

        return jobInfos;

    }

    /**
     * http://localhost:8888/job/add
     *
     * {
     * 	"className": "com.codecoord.springboot.quartz.job.PlanRemindJob",
     * 	"config": "配置信息，例如存储json",
     * 	"cron": "0/3 * * * * ?",
     * 	"jobGroup": "STANDARD_JOB_GROUP",
     * 	"jobName": "计划任务通知任务",
     * 	"triggerGroup": "STANDARD_TRIGGER_GROUP",
     * 	"triggerName": "计划任务通知触发器"
     * }
     *
     * {
     * 	"className": "com.codecoord.springboot.quartz.job.TimeEventJob",
     * 	"config": "配置信息，例如存储json",
     * 	"cron": "0/10 * * * * ?",
     * 	"jobGroup": "STANDARD_JOB_GROUP",
     * 	"jobName": "时间通知任务",
     * 	"triggerGroup": "STANDARD_TRIGGER_GROUP",
     * 	"triggerName": "时间通知触发器"
     * }
     */

    @PostMapping("/add")
    public JobInfo addJob(@RequestBody JobInfo jobInfo) throws ClassNotFoundException, SchedulerException {

        jobHander.addJob(jobInfo);
        return jobInfo;
    }


    @RequestMapping("/pause")
    public void pauseJob(@RequestParam("jobGroup")String jobGroup,@RequestParam("jobName")String jobName) throws SchedulerException {
        jobHander.pauseJob(jobGroup,jobName);
    }


    @RequestMapping("/continue")
    public void continueJob(@RequestParam("jobGroup")String jobGroup,@RequestParam("jobName")String jobName) throws SchedulerException {
        jobHander.continueJob(jobGroup,jobName);
    }


    @RequestMapping("/delete")
    public boolean deleteJob(@RequestParam("jobGroup")String jobGroup,@RequestParam("jobName")String jobName) throws SchedulerException {
        boolean b = jobHander.deleteJob(jobGroup, jobName);
        return b;
    }
}
